﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Net;
using ProgNetComponentsDx.Options;
using System.IO;
using ProgNetComponents.Logs;

namespace BuildHelper
{
    static class Argumenty
    {
        public const string Debug = "-debug";
        public const string NoServer = "-nosrv";
        public const string NoContact = "-nocontact";
        public const string Help2 = "-?";
        public const string Help = "-help";
        public const string NoSingle = "-nosingle";
    }

    static class Program
    {
        private static string[] Args;

        public static bool IsExit
        {
            get;
            set;
        }
        public static bool IsDebug
        {
            get { return IsArgPresent(Argumenty.Debug); }
        }
        public static bool IsServer
        {
            get;
            set;
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 100000;
            RemoveNonWord();
            Args = args;

            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("pl-PL");
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = culture;

            LogType lt = LogType.Error;
            if(IsDebug)
                lt = LogType.All;
            
            Logger.InitDefaultLogger("error.log", lt, lt, IsDebug);
            LoggerProperties p = new LoggerProperties();
            
            p.LogAdditionalStackTrace = ProgNetComponents.Utils.DefaultBool.False;
            p.LogExceptionMessage = ProgNetComponents.Utils.DefaultBool.False;
            p.LogExceptionName = ProgNetComponents.Utils.DefaultBool.False;
            p.LogExceptionProperties = ProgNetComponents.Utils.DefaultBool.False;
            p.LogInnerExceptios = ProgNetComponents.Utils.DefaultBool.False;
            p.LogLogType = ProgNetComponents.Utils.DefaultBool.True;
            p.LogStackTrace = ProgNetComponents.Utils.DefaultBool.False;
            p.LogTime = ProgNetComponents.Utils.DefaultBool.True;
            p.LogDate = ProgNetComponents.Utils.DefaultBool.True;
            p.LogType = LogType.All;
            p.FileName = "kill_process.log";
            Logger.InitLoggerProperties(typeof(System.ProcessExt), p, false);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            
            if (IsArgPresent(Argumenty.Help) || IsArgPresent(Argumenty.Help2))
            {
                string help = Argumenty.Debug + " Funkcje Debug";
                help = help.AppendLine(Argumenty.Help + " | " + Argumenty.Help2 + " Ta pomoc");
                help = help.AppendLine(Argumenty.NoContact + " Brak kontaktów");
                help = help.AppendLine(Argumenty.NoServer + " Nie uruchamia serwera");
            }
            else
            {
                //MessageBox.Show("break");

                Properties.Resources.Build_Helper.SetAsDefaultFormIcon();
                ProgNetComponentsDx.Forms.FormSkinChooser.RegisterSkins();
                ProgNetComponentsDx.SingleAppRunnerDx single = new ProgNetComponentsDx.SingleAppRunnerDx();
                single.MutexName = "Global\\BuildHelper4";
                single.PipeName = "BuildHelper4";

                //Application.Run(new Form1());
                //return;

                if (!IsDebug && !IsArgPresent(Argumenty.NoSingle))
                {
                    single.Run(() => {
                        SetServer();
                        ProgNetComponentsDx.Forms.FormSkinChooser.ApplayStyle(OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne.Styl).AsString(),
               OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne.Skorka).AsString()); 
                        return new FormMain();
                    }, () => { return new Init.InitForm(); });
                }
                else
                {
                    using (Init.InitForm initForm = new Init.InitForm())
                    {
                        initForm.ShowDialog();
                    }
                    SetServer();
                    if (IsDebug)
                    {
                        ProgNetComponentsDx.Browsers.BrowserCache.TestBrowserLng();
                        ProgNetComponentsDx.Data.SelectDataCache.TestDataLng();
                    }
                    ProgNetComponentsDx.Forms.FormSkinChooser.ApplayStyle(OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne.Styl).AsString(),
                OptionCache.GetOptionValue(Init.InitFormOptionNames.Rozne.Skorka).AsString());

                    FormMain main = new FormMain();
                    Application.Run(main);
                    IsExit = true;

                }
            }
            Application.ExitThread();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        private static void SetServer()
        {
            if (Program.IsArgPresent(Argumenty.NoServer))
                IsServer = false;
            else
                IsServer = CheckIsServer();
        }
        private static bool CheckIsServer()
        {
            bool res = false;
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in localIPs)
            {
                if (ip.ToString() == HostIp)
                {
                    res = true;
                    break;
                }
            }
            return res;
        }
        private static string HostIp
        {
            get { return OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Kontakty_Group.Server.HostIp); }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = null;
            if (e.ExceptionObject != null && e.ExceptionObject is Exception)
            {
                ex = e.ExceptionObject as Exception;
            }
            else
            {
                ex = new Exception("Unhandeled exception: " + e.ExceptionObject.AsString());
            }
            ex.Log("==CurrentDomain.UnhandledException==");
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            e.Exception.Log("==Application.ThreadException==");
        }
        
        public static bool IsArgPresent(string arg)
        {
            return Args!=null && Args.Contains(arg);
        }
       
        private static void Copy()
        {
            string str = "c:\\t.txt".ReadFile();
            string[] parts = str.Split('\n');
            string oldFile;
            string newFile;
            string apps= "I:\\nd_src\\GENE\\apps\\";
            string newApps = "C:\\apps\\";
            FileInfo  fNew;

            foreach (string s in parts)
            {
                if (s.IsNotNullOrWhiteSpace())
                {
                    oldFile = apps + s.Trim();
                    newFile = newApps + s.Trim();
                    fNew = new FileInfo(newFile);
                    if (!fNew.Directory.Exists)
                    {
                        fNew.Directory.Create();
                    }
                    File.Copy(oldFile, newFile, true);
                }
            }
        }

        private static void RemoveNonWord()
        {
            System.Reflection.FieldInfo fi = typeof(DevExpress.XtraRichEdit.Model.WordsDocumentModelIterator).GetSingleField("WordsDelimiter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            if (fi != null)
            {
                List<char> WordsDelimiter = fi.GetValue(null) as List<char>;
                try
                {
                    WordsDelimiter.Remove('_');
                }
                catch { }
            }
            fi = typeof(DevExpress.XtraRichEdit.Model.WordsDocumentModelIterator).GetSingleField("NonWordSymbols", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            if (fi != null)
            {
                List<char> NonWordSymbols = fi.GetValue(null) as List<char>;
                try
                {
                    NonWordSymbols.Remove('_');
                }
                catch { }
            }
        }
    }
}

